package com.wld.xm.framework.core.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

/**
 * @author hxj
 * @date 2018/5/4 0004  18:41
 * 上传阿里云
 */
public class OSSUploadThread extends Thread {
    // endpoint以杭州为例，其它region请按实际情况填写
    private String endpoint;
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    private List<FileInputStream> inputStreams;
    private List<String> fileKeys;

    public OSSUploadThread(List<FileInputStream> inputStreams, List<String> fileKeys, String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
        this.inputStreams = inputStreams;
        this.fileKeys = fileKeys;
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.bucketName = bucketName;
    }

    @Override
    public void run() {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            if (null != inputStreams && !inputStreams.isEmpty() && null != fileKeys && !fileKeys.isEmpty()) {
                for (InputStream inputStream : inputStreams) {
                    int index = inputStreams.indexOf(inputStream);
                    if (index < fileKeys.size())
                        ossClient.putObject(bucketName, fileKeys.get(inputStreams.indexOf(inputStream)), inputStream);
                }
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
            throw ce;
        } finally {
            // 关闭client
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
